﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Gfw.Infrastructure.Facilities;
using Gfw.Repositories.Stock;
using Gfw.Repository;

namespace Gfw.Infrastructure.Stock.Facilities
{
    /// <summary>
    /// 股票拆分事务
    /// </summary>
    public class StockSplitFacility : IFacility
    {
        private int _multiple;
    


        /// <summary>
        /// 
        /// </summary>
        /// <param name="multiple">股票拆分多少倍</param>
        public StockSplitFacility(int multiple)
        {
            _multiple = multiple;
        }

        public void Execute(Repository.UnitOfWork unitOfWork = null)
        {
            MarketRepository rep = new MarketRepository();
            var m = rep.Unique();
            decimal newPrice = m.CurrentPrice/_multiple;
            if (Math.Abs(Math.Round(newPrice, 4) - newPrice) != 0)
                throw new Gfw.Infrastructure.ExceptionImpl.GfwTransactionInvalidException("股价不能被倍数除尽，将导致统计数据不准确，不能执行拆分。");


            UnitOfWork work = unitOfWork ?? new UnitOfWork();
         

            //通过Sql完成拆分
            //拆分股票价格
            var market = "UPDATE stk_market SET CurrentPrice=CurrentPrice/" + _multiple;
            work.Session.CreateSQLQuery(market).ExecuteUpdate();

            //拆分公司股
            var admin = "UPDATE stk_adminaccount SET StockCount=StockCount*" + _multiple;
            work.Session.CreateSQLQuery(admin).ExecuteUpdate();

            //拆分股票池记录
            var pool =
                string.Format("UPDATE stk_waitbargainpool SET AgencyPrice=AgencyPrice/{0},AgencyCount=AgencyCount*{0}",
                              _multiple);
            work.Session.CreateSQLQuery(pool).ExecuteUpdate();

            //拆分委托
            var agency =
                string.Format(
                    "UPDATE stk_bargainagency SET AgencyPrice=AgencyPrice/{0},AgencyCount=AgencyCount*{0},TradeCount=TradeCount*{0} where AgencyCount<>TradeCount",
                    _multiple);
            work.Session.CreateSQLQuery(agency).ExecuteUpdate();

            //拆分用户帐户
            var user =
                string.Format(
                    "UPDATE stk_useraccount SET StockCount=StockCount*{0},OriginalStockCount=OriginalStockCount*{0},NextAutoSellPrice=NextAutoSellPrice/{0},LastAutoSellPrice=LastAutoSellPrice/{0}",
                    _multiple);
            work.Session.CreateSQLQuery(user).ExecuteUpdate();

            if (unitOfWork == null)
                work.Commit();

        }
    }
}
